package edu.byu.intex2.data.dao;

import edu.byu.intex2.data.Cache;
import edu.byu.intex2.data.ConnectionPool;
import edu.byu.intex2.data.DataException;
import edu.byu.intex2.data.bo.Manufacturer;
import java.sql.*;

/**
 * Manufacturer Data Access Object
 * @author Brady
 */
public class ManufacturerDAO {

    /////////////////////////////////////////////
    ///   Singleton code
    private static ManufacturerDAO instance = null;

    /** Creates a new instance of ManufacturerDAO */
    private ManufacturerDAO() {
    }//constructor

    /** Retrieves the single instance of this class */
    public static synchronized ManufacturerDAO getInstance() {
        if (instance == null) {
            instance = new ManufacturerDAO();
        }
        return instance;
    }//getInstance

    ////////////////////////////////////////////
    ///   CREATE methods
    /**
     * Creates a new manufacturer in the database */
    public Manufacturer create(String id) throws DataException {
        Manufacturer manufacturer = new Manufacturer(id);
        manufacturer.setObjectAlreadyInDB(false);
        Cache.getInstance().put(manufacturer.getId(), manufacturer);
        return manufacturer;
    }//create


    ////////////////////////////////////////////
    ///   READ methods
    /**
     * Reads an existing manufacturer from the database     */
    public Manufacturer read(String id) throws DataException {
        // Check Cache
        if (Cache.getInstance().containsKey(id)) {
            return (Manufacturer) Cache.getInstance().get(id);
        }

        // Get Connection
        Connection conn = ConnectionPool.getInstance().get();

        // Try Reading with connection
        try {
            return read(id, conn);
        } catch (Exception e) {
            throw new DataException("An error occurred while reading the business object information.", e);
        } finally {
            ConnectionPool.getInstance().release(conn);
        }
    }

    /**
     * Internal method to read an existing manufacturer from the database
     * @return manufacturer
     */
    synchronized Manufacturer read(String id, Connection conn) throws Exception {
        // Check Cache
        if (Cache.getInstance().containsKey(id)) {
            return (Manufacturer) Cache.getInstance().get(id);
        }

        // Prepare a SQL Statement
        PreparedStatement stmt = conn.prepareStatement("SELECT * FROM manufacturer where id=?");

        try {
            stmt.setString(1, id);
            ResultSet rs = stmt.executeQuery(); // execute query
            if (rs.next()) {
                // Read the record with the result set
                return readRecord(rs, conn);
            }//if
            throw new DataException("Manufacturer with id '" + id + "' not found.");
        } finally {
            stmt.close();
        }
    }//read

    /** Internal method to create a manufacturer object from a record  */
    synchronized Manufacturer readRecord(ResultSet rs, Connection conn) throws Exception {
        if (Cache.getInstance().containsKey(rs.getString("id"))) {
            return (Manufacturer) Cache.getInstance().get(rs.getString("id"));
        }
        // Create new manufacturer object
        Manufacturer manufacturer = new Manufacturer(rs.getString("id"));

        // Manufacturer is already in DB
        manufacturer.setObjectAlreadyInDB(true);

        // Put manufacturer in cache
        Cache.getInstance().put(manufacturer.getId(), manufacturer);

        // Set Manufacturer Attributes
        manufacturer.setName(rs.getString("name"));
        manufacturer.setEmail(rs.getString("email"));

        // Manufacturer is dirty and needs to be saved to DB
        manufacturer.setDirty(false);

        return manufacturer;
    }//readRecord


    /////////////////////////////////////////////
    ///   UPDATE methods
    /** Saves an existing manufacturer in the database */
    public void save(Manufacturer manufacturer) throws DataException {
        // get a connection from the pool, save all of the sales first using the other manufacturer method and then commit them in the database
        Connection conn = ConnectionPool.getInstance().get();

        try {
            save(manufacturer, conn); // save with connection
            conn.commit();  // commit the db transaction
        } catch (Exception e) {
            try {
                //rollback if there were any errors saving, catch any other errors you might have
                conn.rollback();
            } catch (SQLException e2) {
                throw new DataException("Could not roll back the manufacturer database transaction!", e2);
            }
            throw new DataException("An error occurred while saving the manufacturer object information.", e);
        } finally {
            // release the connection
            ConnectionPool.getInstance().release(conn);
        }
    }

    /** Internal method to update a manufacturer in the database */
    void save(Manufacturer manufacturer, Connection conn) throws Exception {
        // put the manufacturer object to cache
        Cache.getInstance().put(manufacturer.getId(), manufacturer);

        // decide whether to update or insert into the database
        if (manufacturer.isObjectAlreadyInDB() && manufacturer.isDirty()) {
            update(manufacturer, conn);
        } else if (manufacturer.isDirty()) {
            insert(manufacturer, conn);
        }//if
    }

    /** External method to update or create a manufacturer in the database without committing connection */
    public void saveNoCommit(Manufacturer manufacturer, Connection conn, Boolean alreadyInDB) throws Exception {
        // decide whether to update or insert into the database
        if (alreadyInDB) {
            update(manufacturer, conn);
        } else {
            insert(manufacturer, conn);
        }
    }

    /** Saves an existing manufacturer to the database */
    private void update(Manufacturer manufacturer, Connection conn) throws Exception {
        // use a prepared statement to prevent sql injection
        PreparedStatement stmt = conn.prepareStatement("UPDATE manufacturer SET name=?, email=?  WHERE id=?");
        try {
            // Get Manufacturer Attributes and add them to the statement
            stmt.setString(1, manufacturer.getName());
            stmt.setString(2, manufacturer.getEmail());
            stmt.setString(3, manufacturer.getId());
            stmt.execute();

            // Manufacturer is clean!
            manufacturer.setDirty(false);
        } finally {
            stmt.close();  // make sure to close the prepared statement
        }
    }

    /** Inserts a new manufacturer into the database */
    private void insert(Manufacturer manufacturer, Connection conn) throws Exception {
        PreparedStatement stmt = conn.prepareStatement("INSERT INTO manufacturer (id, name, email) VALUES (?, ?, ?)");
        try {
            // Set Manufacturer Attributes
            stmt.setString(1, manufacturer.getId());
            stmt.setString(2, manufacturer.getName());
            stmt.setString(3, manufacturer.getEmail());
            stmt.execute();

            manufacturer.setObjectAlreadyInDB(true); // now in DB
            manufacturer.setDirty(false); // object is clean
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            stmt.close(); // close the prepared statement
        }
    }

    /////////////////////////////////////////////////
    ///   DELETE methods
    /** We do not support deleting of business objects in this application */
    public void delete(Manufacturer manufacturer) throws DataException {
        throw new RuntimeException("Nice try. The delete function is not supported in this application.");
    }

    ////////////////////////////////////////////////
    ///   SEARCH methods

}
